package com.lhczf.lucenedb;

import com.lhczf.lucenedb.service.DataHub;
import com.lhczf.lucenedb.service.LuceneDbServer;
import com.lhczf.lucenedb.service.LuceneReportServer;
import com.lhczf.lucenedb.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@SpringBootApplication
public class LucenedbApplication {

    public static void main(String[] args) {

        // 启动嵌入式的 Tomcat 并初始化 Spring 环境及其各 Spring 组件
        SpringApplication.run(LucenedbApplication.class, args);

        LuceneDbServer server = SpringUtil.getBean(LuceneDbServer.class);
        DataHub dataHub = SpringUtil.getBean(DataHub.class);

        //init dir
        server.init();

        //init indexWriter and indexSearch
        server.makeWriter();

        String indexDir = SpringUtil.getProperValue("system.lucenedb.index.root");
        String dataDir = SpringUtil.getProperValue("system.lucenedb.data.root");
        server.startProducerThread(dataDir);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String todayStr = LocalDateTime.now().format(formatter);
        StringBuilder sb = new StringBuilder(indexDir);
        sb.append(File.separator).append(LuceneDbServer.INDEX_DAYS_DIR)
                .append(File.separator).append(todayStr);
        server.startConsumerThread(sb.toString());

        String threadName = "lucenedb-thread-integration";
        server.startIntegrationIndexThread(threadName);
        dataHub.putMonitorThreadsMap(threadName, new Object());

        server.startMonitorThread();


        LuceneReportServer luceneReportServer = SpringUtil.getBean(LuceneReportServer.class);
        threadName = "lucenedb-thread-report-manager";
        luceneReportServer.startMergeReportThread(threadName);


    }


    @Configuration
    public static class SecurityPermitAllConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().anyRequest().permitAll().and().csrf().disable();
        }
    }
}
